/**
* @Description: 商品管理(客户)-新增
* @author  tangbin
* @date 2023/4/11
*/

<template>
  <div class="mh100">
    <div class="page-container">

      <el-form ref="form" :model="form" :rules="rules" label-width="88px">
        <!-- 新增商品 -->
        <div class="split-content-info" :style="{minHeight: height + 'px'}">
          <!-- 标题 -->
          <div class="split-content-title clearfix">
            <div class="split-title">
              <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
              <span style="display: inline-block; color: #333333; font-size: 16px;">新增商品</span>
            </div>
          </div>
          <el-row>
            <el-col :span="6">
              <el-form-item label="数据来源:" prop="source">
                <el-select v-model="form.source" placeholder="请选择" size="small" disabled style="width:100%">
                  <el-option
                    v-for="item in dict.type.customer_goods_source"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品编码:" prop="goodsCode">
                <el-input
                  placeholder="请输入"
                  v-model="form.goodsCode"
                  maxlength="50"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品名称:" prop="goodsName">
                <el-input
                  placeholder="请输入"
                  v-model="form.goodsName"
                  maxlength="255"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="替换商品编码:" prop="replaceCode" label-width="104px">
                <el-input
                  placeholder="请输入"
                  v-model="form.replaceCode"
                  maxlength="50"
                  size="small"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <!-- :filter-method="goodsClassFilter" 
                 @focus="goodsClassFocus" -->
              <el-form-item label="商品分类:" prop="goodsClass">
                <el-select ref="classify" v-model="form.goodsClass" placeholder="请选择" size="small"
                 style="width:100%" clearable filterable allow-create default-first-option 
                 :filter-method="goodsClassFilter"
                 @focus="goodsClassFocus"
                 >
                  <el-option
                    v-for="item in goodsClassSet"
                    :key="item"
                    :label="item"
                    :value="item"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格型号:" prop="specsModel">
                <el-input
                  placeholder="请输入"
                  v-model="form.specsModel"
                  maxlength="100"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单位:" prop="defaultUnit">
                <el-select v-model="form.defaultUnit" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.basic_data_goods_default_unit"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <!-- :filter-method="goodsTypeFilter" 
                  @focus="goodsTypeFocus" -->
              <el-form-item label="商品类型:" prop="goodsType">
                <el-select v-model="form.goodsType" placeholder="请选择" size="small" style="width:100%"
                  filterable clearable allow-create default-first-option 
                  :filter-method="goodsTypeFilter"
                  @focus="goodsTypeFocus"
                >
                  <el-option
                    v-for="item in goodsTypeSet"
                    :key="item"
                    :label="item"
                    :value="item"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="生产厂商:" prop="manufacturer">
                <el-input
                  placeholder="请输入"
                  v-model="form.manufacturer"
                  maxlength="100"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="最新进货价:" prop="lastPurchasePrice" label-width="90px">
                <el-input
                  placeholder="请输入"
                  v-model="form.lastPurchasePrice"
                  maxlength="10"
                  size="small"
                  oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                  @blur="form.lastPurchasePrice=$event.target.value"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="平均成本价:" prop="averageCostPrice" label-width="90px">
                <el-input
                  placeholder="请输入"
                  v-model="form.averageCostPrice"
                  maxlength="10"
                  size="small"
                  disabled
                  oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                  @blur="form.averageCostPrice=$event.target.value"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="销售价:" prop="salesPrice">
                <el-input
                  placeholder="请输入"
                  v-model="form.salesPrice"
                  maxlength="10"
                  size="small"
                  oninput="this.value= this.value.match(/\d+(\.\d{0,2})?/) ? this.value.match(/\d+(\.\d{0,2})?/)[0] : ''"
                  @blur="form.salesPrice=$event.target.value"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="仓库:" prop="warehouseId">
                <el-select v-model="form.warehouseId" placeholder="请选择" size="small" @change="warehouseChange" clearable filterable default-first-option style="width:100%">
                  <el-option
                    v-for="item in warehouseOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="货位:" prop="warehouseLocationId">
                <el-select v-model="form.warehouseLocationId" placeholder="请选择" 
                  size="small" style="width:100%"
                  @change="warehouseLocatioinChange"
                  filterable clearable allow-create default-first-option
                  :filter-method="warehouseLocationFilter"
                  @focus="warehouseLocationFocus"
                  @visible-change="warehouseLocationVisibleChange">
                  <el-option
                    v-for="item in storageLocOptions"
                    :key="item.id"
                    :label="item.code"
                    :value="item.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="最小库存:" prop="minNumber" label-width="90px">
                <el-input
                  placeholder="请输入"
                  v-model="form.minNumber"
                  maxlength="10"
                  size="small"
                  oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                  @blur="form.minNumber=$event.target.value"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="最大库存:" prop="maxNumber" label-width="90px">
                <el-input
                  placeholder="请输入"
                  v-model="form.maxNumber"
                  maxlength="10"
                  size="small"
                  oninput="this.value= this.value.match(/\d+/) ? this.value.match(/\d+/)[0] : '';"
                  @blur="form.maxNumber=$event.target.value"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="商品状态:" prop="status">
                <el-select v-model="form.status" placeholder="请选择" size="small" style="width:100%">
                  <el-option
                    v-for="item in dict.type.customer_goods_status"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="图片:" prop="sysObsList">
            <upload-img :lastUrl="uploadUrl" @imageInfo="handleSuccessPicture" :fileLimit="10" :imageData="pictureList"> </upload-img>
          </el-form-item>
          <el-form-item label="备注:" prop="remark">
            <el-input v-model="form.remark" :autosize="{ minRows: 3, maxRows: 12}" type="textarea" placeholder="请输入内容" maxlength="500" show-word-limit></el-input>
          </el-form-item>
        </div>
        
      </el-form>
      




      <div class="h84_line"></div>
      <div class="bottom-btn">
        <div class="bottom-locate" >
          <el-button type="default" @click="cancel">取消</el-button>
          <el-button type="primary" :loading="saveloading" @click="save">确认</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {customerGoodsAdd, customerGoodsOrgs, getTypeAndClassInfos, warehouseList, warehouseCurrentLevelList, warehouseLocList} from '@/api/basic/customerGoods.js'
import {getTimeSeconds} from '@/utils/index.js'

export default {
  name: 'TenantCustomerManageAdd',
  dicts: ['customer_goods_status', 'basic_data_goods_default_unit', 'customer_goods_source'], // 商品状态 单位 数据来源
  data() {
    return {
      mountedTime: undefined, // mounted时间
      activatedTime: undefined, // activated时间
      height: 626,
      saveloading: false, // 点击确认旋转轮
      uploadUrl: '?businessTable=customer_goods_info', // 上传图片的后缀地址
      organizeInfos: [], // 所属组织
      goodsClassSet: [], // 商品分类
      goodsClassSetCopy: [], // 商品分类copy
      unitOptions: [], // 单位
      goodsTypeSet: [], // 商品类型
      goodsTypeSetCopy: [], // 商品类型copy
      warehouseOptions: [], // 仓库
      storageLocOptions: [], // 货位
      storageLocOptionsCopy: [], // 货位copy
      uploadPictureData:[], // 上传图片返回的 
      pictureList: [],
      tip:undefined, // 提示信息
      form: {
        source: 'ONESELF', // 数据来源
        goodsCode: undefined, // 商品编码
        goodsName: undefined, // 商品名称
        replaceCode: undefined, // 替换商品名称
        goodsClass: undefined, // 商品分类
        specsModel: undefined, // 规格型号
        defaultUnit: undefined, // 单位
        defaultUnitName: undefined, // 单位名称
        goodsType: undefined, // 商品类型
        manufacturer: undefined, // 生产厂商
        lastPurchasePrice: undefined, // 最新进货价
        averageCostPrice: undefined, // 平均成本价
        salesPrice: undefined, // 销售价
        warehouseId: undefined, // 仓库
        warehouseLocationId: undefined, // 货位id
        warehouseLocationCode: undefined, // 货位编码
        minNumber: undefined, // 最小库存
        maxNumber: undefined, // 最大库存
        status: undefined, // 商品状态
        sysObsList: [], // 图片
        remark: undefined, // 备注
      },
      rules: {
        goodsCode: [
          {required: true, message: "请输入商品编码", trigger: "blur"}
        ],
        goodsName: [
          {required: true, message: "请输入商品名称", trigger: "blur"}
        ],
        defaultUnit: [
          {required: true, message: "请选择单位", trigger: "change"}
        ],
        salesPrice: [
          {required: true, message: "请输入销售价", trigger: "blur"}
        ],
        status: [
          {required: true, message: "请选择商品状态", trigger: "change"}
        ],
      }
    }
  },
  mounted() {
    this.mountedTime = new Date();
    this.getCustomerGoodsOrgs(); // 查询所属组织和渠道下拉列表
    this.getTypeAndClassInfos(); // 查询商品分类、商品类型下拉列表
    this.getWarehouseList(); // 仓库列表
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  activated() {
    this.activatedTime = new Date();
    let seconds = getTimeSeconds(this.mountedTime, this.activatedTime);
    if (seconds >= 1) {
      this.getCustomerGoodsOrgs(); // 查询所属组织和渠道下拉列表
      this.getTypeAndClassInfos(); // 查询商品分类、商品类型下拉列表
      this.getWarehouseList(); // 仓库列表
    }
    
    // 解决表格设置固定高度导致列设置fixed后重新进来会错行问题
    this.tableHeight();
  },
  methods: {

    tableHeight() {
      this.$nextTick(() => {
        let height = document.body.clientHeight - 90 - 40;// - 62 - 20;
        // 查询表单高度
        let s_height = 0;
        // 按钮容器高度
        // let btns_height = document.getElementById('comTabel').clientHeight;
        // 计算表格的高度
        this.height = height - s_height - 20 - 44;
      });
    },

    /**
     * 输入商品分类得到焦点调用
     * @param {*} e 
     */
     goodsClassFocus(e) {
      this.goodsClassSet = this.goodsClassSetCopy;
    },

    /**
     * 商品分类
     * @param {*} val 
     */
     goodsClassFilter(val) {
      if (val) {
        this.goodsClassSet = this.goodsClassSetCopy.filter((item) => {
          if (!!~item.indexOf(val)) {
            return true;
          }
        });
        if (this.goodsClassSet && this.goodsClassSet.length == 1) {
          this.$nextTick(() => {
            this.form.goodsClass = this.goodsClassSet[0];
          });
        } else {
          if (val.length > 20) {
            this.form.goodsClass = val.slice(0, 20);
          } else {
            this.form.goodsClass = val;
          }
        }
      } else {
        this.form.goodsClass = undefined;
        this.goodsClassSet = this.goodsClassSetCopy;
      }
    },

    /**
     * 输入商品类型得到焦点调用
     * @param {*} e 
     */
     goodsTypeFocus(e) {
      this.goodsTypeSet = this.goodsTypeSetCopy;
    },

    /**
     * 商品类型
     * @param {*} val 
     */
     goodsTypeFilter(val) {
      if (val) {
        this.goodsTypeSet = this.goodsTypeSetCopy.filter((item) => {
          if (!!~item.indexOf(val)) {
            return true;
          }
        });
        if (this.goodsTypeSet && this.goodsTypeSet.length == 1) {
          this.$nextTick(() => {
            this.form.goodsType = this.goodsTypeSet[0];
          });
        } else {
          if (val.length > 20) {
            this.form.goodsType = val.slice(0, 20);
          } else {
            this.form.goodsType = val;
          }
        }
      } else {
        this.form.goodsType = undefined;
        this.goodsTypeSet = this.goodsTypeSetCopy;
      }
    },

    /**
     * 货位有焦点
     * @param {*} e 
     */
    warehouseLocationFocus(e) {
      this.storageLocOptions = this.storageLocOptionsCopy;
    },

    /**
     * 货位搜索
     * @param {*} val 
     */
    warehouseLocationFilter(val) {
      console.log('val=', val);
      // console.log('storageLocOptions=', this.storageLocOptions);
      if (val) {
        this.storageLocOptions = this.storageLocOptionsCopy.filter((item) => {
          if (!!~item.code.indexOf(val)) {
            return true;
          }
        });
        if (this.storageLocOptions && this.storageLocOptions.length == 1) {
          this.$nextTick(() => {
            this.form.warehouseLocationId = this.storageLocOptions[0].id;
            this.form.warehouseLocationCode = this.storageLocOptions[0].code;
          });
        } else {
          // console.log('2222222');
          // if (val.length > 20) {
          //   this.form.goodsType = val.slice(0, 20);
          // } else {
            this.form.warehouseLocationId = val;
            this.form.warehouseLocationCode = val;
          // }
        }
      } else {
        this.form.warehouseLocationId = undefined;
        this.form.warehouseLocationCode = undefined;
        this.storageLocOptions = this.storageLocOptionsCopy;
      }
    },

    /**
     * 上传图片
     */
     handleSuccessPicture(response) {
      this.uploadPictureData = response;
    },

    /**
      * 查询所属组织和渠道下拉列表
      */
    getCustomerGoodsOrgs() {
      customerGoodsOrgs().then(res => {
        if (res.code == 200) {
          if (res.code == 200) {
          this.organizeInfos = (res.data.organizeInfo ? res.data.organizeInfo : []);
        }
        }
      }).catch(err => {

      });
    },
    
    /**
     * 查询商品分类、商品类型下拉列表
     */
    getTypeAndClassInfos() {
      getTypeAndClassInfos().then(res => {
        // console.log('查询商品分类、商品类型下拉列表=', res);
        if (res.code == 200) {
          this.goodsClassSet = (res.data.goodsClassSet ? res.data.goodsClassSet : []); // 商品分类
          this.goodsTypeSet = (res.data.goodsTypeSet ? res.data.goodsTypeSet : []); // 商品类型
          this.goodsClassSetCopy = JSON.parse(JSON.stringify(this.goodsClassSet));
          this.goodsTypeSetCopy = JSON.parse(JSON.stringify(this.goodsTypeSet));
        }
      }).catch(err => {

      });
    },

    // dict.type.basic_data_goods_default_unit

    /**
     * 得到单位名称
     * @param {*} value 
     */
    getGoodsDefaultUnitName(value) {
      let show = undefined;
      this.dict.type.basic_data_goods_default_unit.some((item) => {
        if (item.value === value) {
          show = item.label;
          return true;
        }
      });
      return show;
    },

    /**
     * 查询仓库列表
     */
     getWarehouseList() {
      warehouseCurrentLevelList({status: 'ENABLE'}).then(res => {
        // console.log('仓库列表=', res);
        if (res.code == 200) {
          this.warehouseOptions = res.data;
        }
      }).catch(err => {

      });
    },

    /**
     * 选择仓库chang出发
     * @param {*} val 
     */
    warehouseChange(val) {
      this.getWarehouseLocList(val);
    },

    /**
     * 货位改变的时候
     * @param {*} val 
     */
    warehouseLocatioinChange(val) {
      // console.log('val===', val);
      this.storageLocOptionsCopy.some(item => {
        if (item.id == val) {
          this.warehouseLocationCode = item.code;
          return true;
        }
      });
    },

    /**
     * 货位 下拉框出现/隐藏时触发
     * @param {*} val 
     */
    warehouseLocationVisibleChange(val) {
      // console.log('val===', val);
      if (val == true) {
        this.storageLocOptions = this.storageLocOptionsCopy;
      }
    },

    /**
     * 货位列表查询
     */
    getWarehouseLocList(warehouseId) {
      // console.log('warehouseId=', warehouseId);
      warehouseLocList({warehouseId: warehouseId}).then(res => {
        // console.log('货位=', res);
        if (res.code == 200) {
          this.form.warehouseLocationId = undefined;
          this.storageLocOptions = res.data;
          this.storageLocOptionsCopy = JSON.parse(JSON.stringify(res.data));
        }
      }).catch(err => {

      });
    },

    /**
     * 选择仓库chang出发
     * @param {*} val 
     */
    warehouseChange(val) {
      this.getWarehouseLocList(val);
    },

    /**
     * 取消
     */
    cancel() {
      const obj = { path: "/basicData/tenantCustomerManage" };
      this.$tab.closeOpenPage(obj);
    },

    /**
     * 保存
     */
    save() {


      const lastPurchasePrice = Number(this.form.lastPurchasePrice ? this.form.lastPurchasePrice : 0); // 最新进货价
      const averageCostPrice = Number(this.form.averageCostPrice ? this.form.averageCostPrice : 0); // 平均成本价
      const salesPrice = Number(this.form.salesPrice ? this.form.salesPrice : 0); // 销售价
      // 销售价低于最新进货价、平均成本价，确定提交？
      this.tip = undefined;
      if (salesPrice < lastPurchasePrice && salesPrice < averageCostPrice) {
        this.tip = '销售价低于最新进货价、平均成本价，确定提交？';
      } else if (salesPrice < lastPurchasePrice) {
        this.tip = '销售价低于最新进货价，确定提交？';
      } else if (salesPrice < averageCostPrice) {
        this.tip = '销售价低于平均成本价，确定提交？';
      }

      if (this.tip !== undefined) {
        this.$confirm(this.tip, '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.saveSubmit();
        }).catch(action => {

        });
      } else {
        this.saveSubmit();
      }
    },

    /**
     * 保存提交
     */
    saveSubmit() {

      if (this.form.warehouseLocationCode && this.form.warehouseLocationCode.length > 0) {
        if (this.form.warehouseId === undefined || this.form.warehouseId === null || this.form.warehouseId === '') {
          this.$modal.msgWarning('请先选择仓库！');
          return;
        }
      }

      if (Number(this.form.maxInventory || 0) < Number(this.form.minInventory || 0)) {
        this.$modal.msgWarning('最大仓库需大于最小仓库');
        return;
      }

      this.form.sysObsList = [];
      this.uploadPictureData && this.uploadPictureData.forEach(item => {
        this.form.sysObsList.push(
          {
            id: item.id,
            objectOriginalName: item.name,
            objectSize: item.size,
            objectUrl: item.url
          }
        );
      });
      // 得到单位名称
      this.form.defaultUnitName = this.getGoodsDefaultUnitName(this.form.defaultUnit);
      this.$refs['form'].validate(valid => {
        if (!valid) {
          this.saveloading = false;
          return;
        }
        // console.log('form=', this.form);
        
        this.saveloading = true;
        let params = JSON.parse(JSON.stringify(this.form));
        if (this.form.warehouseLocationCode == this.form.warehouseLocationId) {
          params.warehouseLocationId = undefined;
        } else {
          params.warehouseLocationCode = undefined;
        }
        customerGoodsAdd(params).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess('添加商品成功！');
            this.cancel();
          } else {
            this.$modal.msgError('添加商品失败！');
          }
          this.saveloading = false;
        }).catch(err => {
          this.saveloading = false;
        });
      });
    },
  },
}

</script>

<style lang="scss" scoped>

</style>